package com.bishe.demo.modules.account.service.impl;

import com.bishe.demo.modules.account.dao.UserDao;
import com.bishe.demo.modules.account.dao.UserRoleDao;
import com.bishe.demo.modules.account.entity.User;
import com.bishe.demo.modules.account.entity.UserRole;
import com.bishe.demo.modules.account.service.UserService;
import com.bishe.demo.modules.common.entity.ResultEntity;
import com.bishe.demo.modules.common.entity.SearchBean;
import com.bishe.demo.util.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Collections;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    @Transactional
    public ResultEntity<User> register(User user) {
        User u = userDao.getUserByUserName(user.getUserName());
        if (u == null) {
            user.setPassword(MD5Util.getMD5(user.getUserName(), user.getPassword()));
            user.setUserImage("/upload/tx/moren.jpg");
            userDao.insertUser(user);
            userRoleDao.insertUserRole(new UserRole(user.getUserId(), 2));
            return new ResultEntity<User>(ResultEntity.ResultStatus.SUCCESS.code, "注册成功", user);
        }
        return new ResultEntity<User>(ResultEntity.ResultStatus.FAILED.code, "账号已存在");
    }

    @Override
    public ResultEntity<User> login(User user) {
        user.setPassword(MD5Util.getMD5(user.getUserName(), user.getPassword()));
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        token.setRememberMe(user.isRememberMe());
        try {
            subject.login(token);
            subject.checkRoles();

            Session session = subject.getSession();
            session.setAttribute("user", subject.getPrincipal());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultEntity<User>(ResultEntity.ResultStatus.FAILED.code, String.format("用户不存在或密码错误"));
        }
        return new ResultEntity<User>(ResultEntity.ResultStatus.SUCCESS.code, "login success.", (User) subject.getPrincipal());
    }

    @Override
    @Transactional
    public ResultEntity<User> updateUserPassword(User user) {
        user.setPassword(MD5Util.getMD5(user.getUserName(), user.getPassword()));
        userDao.updateUserPassword(user);
        return new ResultEntity<User>(ResultEntity.ResultStatus.SUCCESS.code, "修改密码成功", user);
    }

    @Override
    @Transactional
    public ResultEntity<User> updateUserInfo(User user) {
        userDao.updateUserInfo(user);
        if (user.getRole() != null) {
            userRoleDao.deleteUserRoleByUserId(user.getUserId());
            userRoleDao.insertUserRole(new UserRole(user.getUserId(), user.getRole().getRoleId()));
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("user", user);
        return new ResultEntity<User>(ResultEntity.ResultStatus.SUCCESS.code, "修改成功", user);
    }

    @Override
    @Transactional
    public ResultEntity<User> deleteUserByUserId(int userId) {
        userDao.deleteUserByUserId(userId);
        userRoleDao.deleteUserRoleByUserId(userId);
        return new ResultEntity<User>(ResultEntity.ResultStatus.SUCCESS.code, "删除成功");
    }

    @Override
    public User getUserByUserId(int userId) {
        return userDao.getUserByUserId(userId);
    }

    @Override
    public User getUserByUserName(String userName) {
        return userDao.getUserByUserName(userName);
    }

    @Override
    public PageInfo<User> getUsersBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getCurrentPage(), searchBean.getPageSize());
        return new PageInfo<User>(Optional
                .ofNullable(userDao.getUsersBySearchBeans(searchBean))
                .orElse(Collections.emptyList()));
    }

    @Override
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
}
